package top.broncho.gank.ui.fragment

import android.app.Application
import androidx.lifecycle.MutableLiveData
import top.broncho.gank.api.ApiService
import top.broncho.gank.bean.AllTodoResponseBody
import top.broncho.gank.bean.TodoResponseBody
import top.broncho.gank.http.exception.ErrorStatus
import retrofit2.Retrofit
import retrofit2.create
import top.broncho.mvvm.base.BaseViewModel
import javax.inject.Inject

class TodoViewModel @Inject constructor(app: Application, private val retrofit: Retrofit) :
    BaseViewModel(app) {
    private val api by lazy { retrofit.create<ApiService>() }

    val allTodoList = MutableLiveData<Result<AllTodoResponseBody>>()
    val noTodoList = MutableLiveData<Result<TodoResponseBody>>()
    val doneTodoList = MutableLiveData<Result<TodoResponseBody>>()
    val deleteTodo = MutableLiveData<Result<Any>>()
    val updateTodo = MutableLiveData<Result<Any>>()

    fun getAllTodoList(type: Int) = launchOnlyResult(
        block = {
            api.getTodoList(type)
        },
        success = {
            allTodoList.postValue(Result.success(it))
        },
        error = {
            allTodoList.postValue(Result.failure(it))
        }
    )

    fun getNoTodoList(page: Int, type: Int) = launchOnlyResult(
        block = {
            api.getNoTodoList(page, type)
        },
        success = {
            noTodoList.postValue(Result.success(it))
        },
        error = {
            noTodoList.postValue(Result.failure(it))
        }
    )

    fun getDoneList(page: Int, type: Int) = launchOnlyResult(
        block = {
            api.getDoneList(page, type)
        },
        success = {
            doneTodoList.postValue(Result.success(it))
        },
        error = {
            doneTodoList.postValue(Result.failure(it))
        }
    )

    fun deleteTodoById(id: Int) = launchOnlyResult(
        block = {
            api.deleteTodoById(id)
        },
        success = {
            deleteTodo.postValue(Result.success(it))
        },
        error = {
            deleteTodo.postValue(Result.failure(it))
        }
    )

    fun updateTodoById(id: Int, status: Int) = launchOnlyResult(
        block = {
            api.updateTodoById(id, status)
        },
        success = {
            updateTodo.postValue(Result.success(it))
        },
        error = {
            updateTodo.postValue(Result.failure(it))
        }
    )
}